﻿using System;
using BO.Infrastructure.StaticData;
using BO.Infrastructure.Utils;
using BO.News;
using BO.Solr;
using ChannelVN.Cached.UrlRewrite;
using GUI.Extensions;
using Utilities.Entities;
using System.Text.RegularExpressions;

namespace GUI.Pages.News
{
    public partial class ListNewsByTag : System.Web.UI.Page
    {
        private const int PageSize = 15;
        private const int TopHighlight = 3;
        public string DetailedUrl { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Regex.IsMatch(Request.RawUrl, "[A-Z]+"))
            {
                _301Redirection.RedirectTo(Request.RawUrl.ToLower());
                return;
            }
            var tagUrl = RequestExtensions.TagUrl;

            if (!string.IsNullOrEmpty(tagUrl))
            {
                var pageIndex = RequestExtensions.PageIndex;
                var containsPageIndex = RequestExtensions.ContainsPageIndex;

                {
                    var searchResult = SolrBO.SearchNewsByTag(
                        tagUrl: tagUrl,
                        pageIndex: 1,
                        pageSize: TopHighlight);
                    if (searchResult != null && searchResult.response != null)
                        ctrHighlightNews.Visible = ctrHighlightNews.DataBind(searchResult.response.docs);
                    else
                    {
                        ctrHighlightNews.Visible = false;
                    }

                }
                {
                    TagObject objTag = null;
                    SearchResult searchResult = null;
                    if (ctrHighlightNews.Visible)
                    {
                        searchResult = SolrBO.SearchNewsByTag(
                            tagUrl: tagUrl,
                            pageIndex: pageIndex,
                            pageSize: PageSize,
                            topExclusion: TopHighlight);

                        objTag = NewsBO.GetTagMetaData(tagUrl);

                        if (searchResult != null && searchResult.response.numFound > 0)
                        {
                            var docs = searchResult.response.docs;

                            if (docs == null || docs.Length == 0)
                            {
                                var url = string.Format("/{0}/page-{1}.html", tagUrl,
                                                        (int)Math.Ceiling((double)searchResult.response.numFound / PageSize));
                                _301Redirection.RedirectTo(url.ToLower());
                                return;
                            }

                            if (objTag == null)
                            {

                                if (docs.Length > 0)
                                {
                                    var result = docs[0];
                                    for (var i = 0; i < result.Tags.Length; i++)
                                    {
                                        var tag = result.Tags[i];
                                        if (tag.Equals(tagUrl, StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            objTag = new TagObject
                                                {
                                                    Name = result.TagItem[i],
                                                    DisplayUrl = tagUrl,
                                                    Url = PresentationUtils.UrlBuilder.BuildTagUrl(tagUrl, false),
                                                    Description = result.Sapo,
                                                    Title = string.Format("{0}: {1}", result.TagItem[i], result.Title),
                                                    DetailedAvatar = PresentationUtils.Photo.GetSourceImage(result.Avatar),
                                                    Keywords =
                                                        string.Format("{0},{1}", result.TagItem[i], tagUrl.Replace('-', ' '))
                                                };
                                            NewsBO.AddTagMetaData(objTag);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                    }
                    if (objTag != null)
                    {
                        ltrTagName.Text = objTag.Name;
                        if (searchResult != null)
                        {
                            ctrListNews.Visible = ctrListNews.DataBind(searchResult.response.docs, objTag.Name);
                            ctrPaging.SumPage = (int)Math.Ceiling((double)searchResult.response.numFound / PageSize);
                            ctrPaging.LinkSite = RequestExtensions.Url;
                            ctrPaging.Padding(pageIndex, ".html");
                        }

                        //tagInfo nhập từ CMS
                        var tagInfo = NewsBO.GetInstance().GetTagDetail(objTag.DisplayUrl);
                        if (tagInfo != null &&
                            (!string.IsNullOrEmpty(tagInfo.Avatar) || !string.IsNullOrEmpty(tagInfo.Content)))
                        {
                            ltrTagAvatar.Text = PresentationUtils.Photo.BuildPhoto(tagInfo.Avatar, tagInfo.Name, 300, 0);
                            ltrTagBody.Text = tagInfo.Content;
                            if (!string.IsNullOrEmpty(tagInfo.Title))
                                objTag.Title = tagInfo.Title;
                            if (!string.IsNullOrEmpty(tagInfo.Description))
                                objTag.Description = tagInfo.Description;
                            if (!string.IsNullOrEmpty(tagInfo.Keywords))
                                objTag.Keywords = tagInfo.Keywords;
                            if (!string.IsNullOrEmpty(tagInfo.Avatar))
                                objTag.DetailedAvatar = PresentationUtils.Photo.GetSourceImage(tagInfo.Avatar);
                        }
                        else
                        {
                            divTagInfo.Visible = false;
                        }

                        ctrGoogleSnippet.Avatar = objTag.DetailedAvatar;
                        ctrGoogleSnippet.Url = DetailedUrl =  PresentationUtils.UrlBuilder.BuildAbsoluteUrl(objTag.Url);
                        ctrGoogleSnippet.Title = objTag.Title;
                        ctrGoogleSnippet.Description = objTag.Description;

                        #region Title/MetaData

                        var extraText = containsPageIndex ? string.Format(" | page {0}", pageIndex) : string.Empty;
                        Page.Header.Title = string.Format("{0} | soha.vn{1}", objTag.Title, extraText);
                        PresentationUtils.AddMeta(Page, DefinedConstants.MetaAttributes.Description.Id,
                                                  DefinedConstants.MetaAttributes.Description.Name,
                                                  objTag.Description + extraText);
                        PresentationUtils.AddMeta(Page, DefinedConstants.MetaAttributes.Keywords.Id,
                                                  DefinedConstants.MetaAttributes.Keywords.Name, objTag.Keywords);

                        #endregion
                    }
                    else
                    {
                        var title = string.Format("{0}: Tin tức, hình ảnh, video mới nhất về {0}",
                                                  tagUrl.Replace('-', ' '));
                        Page.Header.Title = string.Format("{0} | soha.vn", title);
                        PresentationUtils.AddMeta(Page, DefinedConstants.MetaAttributes.Description.Id,
                                                  DefinedConstants.MetaAttributes.Description.Name, tagUrl);
                        PresentationUtils.AddMeta(Page, DefinedConstants.MetaAttributes.Keywords.Id,
                                                  DefinedConstants.MetaAttributes.Keywords.Name, tagUrl);
                        ltrTagName.Text = "Chưa có bài viết nào thuộc tag này.";
                        divTagInfo.Visible = false;
                    }
                }
                return;
            }

            _301Redirection.RedirectToFileNotFoundPage();
        }
    }
}
